package com.sakura.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sakura.po.TextMessage;
import com.sakura.util.CheckUtil;
import com.sakura.util.MessageUtil;

@Controller
@RequestMapping("wechatpublic")
public class WeChatPublicController {
	
	/**
	 * 微信公众号验证服务器配置方法
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	/*@RequestMapping(value = "/wechatsign", method = RequestMethod.GET)
	public String weChatSign(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		PrintWriter out = response.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		return null;
	}*/

	/**
	 * 接收微信消息并回复消息的方法
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/wechatsign", method = RequestMethod.POST)
	public String receiveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		try {
			Map<String, String> map = MessageUtil.xmlToMap(request);
			String toUserName = map.get("ToUserName");
			String fromUserName = map.get("FromUserName");
//			String createTime = map.get("CreateTime");
//			String content = map.get("Content");
			String msgType = map.get("MsgType");
			
			String message = null;
			if (StringUtils.equals(msgType, "text")) {
				TextMessage textMessage = new TextMessage();
				textMessage.setFromUserName(toUserName);
				textMessage.setToUserName(fromUserName);
				textMessage.setMsgType("text");
				textMessage.setContent("已经收到消息了！");
				textMessage.setCreateTime(new Date().getTime());
				message = MessageUtil.textMessageToXml(textMessage);
			}
			out.print(message);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
		return null;
	}
}
